package com.qire.manhua.controller;

import android.text.InputType;
import android.view.KeyEvent;
import android.view.View;
import android.view.animation.BounceInterpolator;
import android.widget.CheckBox;
import android.widget.EditText;

import com.qire.antsrouter.AntsRouter;
import com.qire.antsrouter.card.FloorCard;
import com.qire.common.support.DialogFastBuildUtil;
import com.qire.common.support.base.EventController;
import com.qire.common.constant.Navigation;
import com.qire.common.constant.Url;
import com.qire.common.utils.ToastHelper;
import com.qire.manhua.R;
import com.qire.manhua.activity.LoginGuideActivity;
import com.qire.manhua.databinding.ActivityLoginGuideBinding;
import com.qire.manhua.model.enumeration.AccountBusinessPanelLayout;
import com.qire.manhua.model.viewModel.impl.LoginGuideViewModel;
import com.qire.manhua.view.CompoundEventEditText;
import com.qire.manhua.view.CompoundEventEditText.EventDrawable;

public class LoginGuideController extends EventController<LoginGuideActivity> {

    private LoginGuideViewModel viewModel;
    private ActivityLoginGuideBinding viewDataBinder;

    public LoginGuideController(LoginGuideActivity activity) {
        super(activity);
    }

    @Override
    protected void bindView() {
        viewDataBinder = owner.viewDataBinder();
        viewDataBinder.setLoginGuideController(this);
    }

    @Override
    protected void onCleared() {
        super.onCleared();
        this.viewModel = null;
        this.viewDataBinder = null;
    }

    public void bindViewModel(LoginGuideViewModel viewModel) {
        this.viewModel = viewModel;
    }

    /**
     * 返回按钮事件
     * @param view
     */
    public void backBtnOnClick(View view) {
        viewModel.backPage();
    }

    /**
     * 复合编辑控件，查看密码功能时间监听
     * @param view
     * @param eventDrawable
     * @return
     */
    public boolean compoundEventPlaintextBtnOnClick(CompoundEventEditText view, EventDrawable eventDrawable) {
        int inputType = view.getInputType();

        int visiblePassword = InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD;
        int invisiblePassword = InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD;

        if(inputType != visiblePassword) {
            view.setInputType(visiblePassword);
            eventDrawable.setDrawableResId(R.drawable.app_compound_icon_pwd_plaintext);
        } else {
            view.setInputType(invisiblePassword);
            eventDrawable.setDrawableResId(R.drawable.app_compound_icon_pwd_ciphertext);
        }
        view.setSelection(view.getText().length());
        return true;
    }

    /**注册密码按钮事件响应*/
    public void phoneRegisterBtnOnClick(View view) {
        viewModel.phoneRegister();
    }

    /**忘了密码按钮事件响应*/
    public void forgotPasswordBtnOnClick(View view) {
        AccountBusinessPanelLayout.RetrievePassword.addNext(AccountBusinessPanelLayout.PhoneLogin);
        AccountBusinessPanelLayout.CodeVerify.addNext(AccountBusinessPanelLayout.RetrievePassword);
        viewModel.gotoPage(AccountBusinessPanelLayout.CodeVerify);
        viewModel.fetchVerificationCode();
    }

    /**QQ登录方式按钮事件响应*/
    public void qqButtonOnClick(View view) {
        DialogFastBuildUtil.Builder builder = DialogFastBuildUtil.builder(owner, R.layout.dialog_login_agree_protocol_tips);
        builder.setTextView(R.id.userProtocol, this::userProtocolReadBtnOnClick)
                .setTextView(R.id.privacyPolicy, this::privacyPolicyReadBtnOnClick)
                .setTextView(R.id.dialog_firstButton, "取消", v -> builder.dismiss())
                .setTextView(R.id.dialog_secondButton, "同意并继续", v -> viewModel.qqLogin())
                .show();
    }
    /**微信登录方式按钮事件响应*/
    public void weChatButtonOnClick(View view) {
        DialogFastBuildUtil.Builder builder = DialogFastBuildUtil.builder(owner, R.layout.dialog_login_agree_protocol_tips);
        builder.setTextView(R.id.userProtocol, this::userProtocolReadBtnOnClick)
                .setTextView(R.id.privacyPolicy, this::privacyPolicyReadBtnOnClick)
                .setTextView(R.id.dialog_firstButton, "取消", v -> builder.dismiss())
                .setTextView(R.id.dialog_secondButton, "同意并继续", v -> viewModel.weChatLogin())
                .show();
    }

    /**手机认证按钮事件响应*/
    public void phoneAuthBtnOnClick(View view) {
        if (!viewModel.isAgreeProtocol()) {
            final CheckBox agreeProtocolCheck = viewDataBinder.agreeProtocolCheck;

            DialogFastBuildUtil.Builder builder = DialogFastBuildUtil.builder(owner, R.layout.dialog_login_agree_protocol_tips);
            builder.setTextView(R.id.userProtocol, this::userProtocolReadBtnOnClick)
                    .setTextView(R.id.privacyPolicy, this::privacyPolicyReadBtnOnClick)
                    .setTextView(R.id.dialog_firstButton, "取消", v -> builder.dismiss())
                    .setTextView(R.id.dialog_secondButton, "同意并继续", v -> {
                        builder.dismiss();
                        agreeProtocolCheck.setChecked(true);
                        agreeProtocolCheck.setScaleX(0.5f);
                        agreeProtocolCheck.setScaleY(0.5f);
                        agreeProtocolCheck.animate().scaleX(1f).scaleY(1f).setDuration(500)
                                .setInterpolator(new BounceInterpolator())
                                .start();
                        view.setClickable(false);
                        agreeProtocolCheck.postDelayed(() -> {
                            view.setClickable(true);
                            phoneAuthBtnOnClick(view);
                        }, 500);
                    }).show();
            return;
        }
        if (!viewModel.phoneIsValid()) {
            ToastHelper.showToast("手机号码输入错误");
            viewModel.resetGetCodeButton();
            return;
        }

        viewModel.phoneAuth();
    }

    /**验证码验证按钮事件响应*/
    public void verifyBtnOnClick(View view) {
        viewModel.checkVerificationCode();
    }

    /**跳过按钮事件响应*/
    public void skipBtnOnClick(View view) {
        viewModel.switchPage();
    }

    /**用户昵称设置按钮事件响应*/
    public void nicknameSetBtnOnClick(View view) {
        viewModel.updateNickname();
    }

    /**登录按钮事件响应*/
    public void loginBtnOnClick(View view) {
        viewModel.mobileLogin();
    }

    /**获取验证码*/
    public void fetchVerifyCodeBtnOnClick(View view) {
        viewModel.fetchVerificationCode();
    }

    /**找回密码按钮事件响应*/
    public void retrievePasswordBtnOnClick(View view) {
        viewModel.retrievePasswordAction();
    }

    /**设置密码按钮事件响应:老旧账户没有设置密码，需要在此设置密码*/
    public void setPasswordBtnOnClick(View view) {
        viewModel.updatePasswordAction();
    }

    /**用户协议阅读按钮事件响应*/
    public void userProtocolReadBtnOnClick(View view) {
        AntsRouter.ROUTER.<FloorCard>buildCard(Navigation.Page.WebPage)
                .withData("title", "用户协议")
                .withData("url", Url.serviceTerms_url)
                .navigation();
    }

    /**
     * 隐私协议阅读按钮事件响应
     */
    public void privacyPolicyReadBtnOnClick(View view) {
        AntsRouter.ROUTER.<FloorCard>buildCard(Navigation.Page.WebPage)
                .withData("title","隐私协议")
                .withData("url",Url.privacyPolicy_url)
                .navigation();
    }




    public void verifyCodeOnFocusChange(View view, boolean hasFocus) {
        if(hasFocus) {
            view.setBackgroundResource(R.drawable.app_common_edit_verify_code_n);
        } else {
            view.setBackgroundResource(R.drawable.app_common_edit_verify_code_s);
        }
    }
    //解决光标在最前面的位置导致退格键失效的问题
    public boolean verifyCodeOnKey(View view, int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_DEL) {
            EditText editText = (EditText) view;
            int textLength = editText.getText().toString().length();
            if(textLength > 0) {
                editText.setSelection(textLength);
            } else {
                editText.setText("");
            }
        }
        return false;
    }

}
